package de.se.ludoapp.activity.task;

import java.util.ArrayList;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.VisitorTableActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.GameListResponse;

/**
 * 
 * @author L.Rother
 * 
 */
public class RunningGamesTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private VisitorTableActivity context;
	private ArrayList<Game> gamelist;

	public RunningGamesTask(LudoApplication ludoApp,
			VisitorTableActivity context) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.gamelist = null;
	}

	/**
	 * Running Games from server
	 * 
	 * @param params
	 * @return
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute getRunningGames */
		GameListResponse response = ludoApp.getLudoStub().getRunningGames();
		if (response.getReturnCode() == 0) {
			gamelist = response.getGamelist();
		}
		return response.getMsg();
	}

	/**
	 * Show running games as list. <br>
	 * This method is called, if RunningGamesTask is executed.
	 */
	protected void onPostExecute(String result) {
		if (gamelist != null) {
			ListAdapter adapter = new ArrayAdapter(context,
					android.R.layout.simple_list_item_1, gamelist);
			ListView listViewOpenGames = (ListView) context
					.findViewById(R.id.listViewRunningGames);
			listViewOpenGames.setAdapter(adapter);
		} else {
			TextView textView = (TextView) context
					.findViewById(R.id.listViewRunningGames);
			textView.setText(textView.getText() + " " + result);
		}
	}

}
